<?php
class RoleModel extends Zend_Db_Table
{
	protected $_name;      //表名
	protected $_primary;   //主键
	
	private $_output;
	
	protected function _setup()
	{
		$this->_name = 'st_role';
		$this->_primary = 'id';
		
		$this->_output = new Custom_Controller_Plugin_Output();
		parent::_setup();
	}
	
	/**
	 * 用于easyui分页
	 * 
	 * @param array $data 过滤数组
	 * 
	 * @return Zend_Db_Table_Rowset_Abstract
	 */
	public function pageRow($data)
	{
		//严格约定，数组键值与字段名必须一致
		$data['page'] = intval($data['page']) - 1;
		
		$db = $this->getAdapter();
		$select = new Zend_Db_Select($db);
		
		$select->from('st_role', array('id', 'role_name'));
		if(isset($data['search']) && !empty($data['search']))
		{
			$search = json_decode($data['search'], true);
			$select->where('role_name like ?', '%'.$search['role_name'].'%');
		}
		
		$select->order($data['sort'].' '.$data['order']);
		$select->limit($data['rows'], $data['page']);

		return $db->fetchAll($select);
	}
	
	
	public function row($id = null)
	{
		$db = $this->getAdapter();
		$select = new Zend_Db_Select($db);
		
		$select->from('st_role');
		$select->where('id=?', $id);
		$select->limit(1);
		
		$rows = $db->fetchRow($select);
		$rows['role_permission'] = unserialize($rows['role_permission']);
		
		return $rows;
	}
	
	public function rows()
	{
		$db = $this->getAdapter();
		$select = new Zend_Db_Select($db);
		$select->from('st_role', array('id', 'role_name'));
		
		return $db->fetchAll($select);
	}
	
	public function getPermission($id, $data)
	{
		$rows = $this->row($id);
		$acl = $rows['role_permission'];
		
		$permission = array();
		
		foreach($data['data'] as $key => $val)
		{
			
			$val = @explode('_', $val);
			$resource = isset($val[0]) ? $val[0]:null;
			$ac = isset($val[1]) ? $val[1]:null;
			
			if($acl->hasRole($data['role']) && $acl->has($resource)
					&& $acl->isAllowed($data['role'], $resource, $ac))
			{
				$permission[$key] = true;
			}
			else
			{
				$permission[$key] = false;
			}
			
		}
		
		$this->_output->display(json_encode($permission));
	}
	
	public function addRole($data)
	{
		//获取权限对象
		$acl = new Custom_Controller_Plugin_ACLRole();
		$result = $acl->setACL($data);
		
		if(!empty($result)) 
		{
			$data['role_permission'] = $result;
			$this->insert($data);
			return $this->_output->success(true);
		}
		
		return $this->_output->success(false, '添加角色失败');
	}
	
	public function editRole($id, $data)
	{
		//获取权限对象
		$acl = new Custom_Controller_Plugin_ACLRole();
		$result = $acl->setACL($data);
		
		if(!empty($result)) 
		{
			$data['role_permission'] = $result;
			$where = $this->_db->quoteInto('id=?', $id);
			
			$this->update($data, $where);
			return $this->_output->success(true);
		}
		
		return $this->_output->success(false, '修改角色失败');
	}
	
	public function deleteRole($id)
	{
		$where = $this->_db->quoteInto('id IN(?)', $id);
		$this->delete($where);
		
		return $this->_output->success(true);
	}
}